package cn.edu.zut.soft.graduate.filter;

import org.apache.commons.lang.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;

/**
 * 坑爹的跨域 这里直接判断请求的origin 如果合法(匹配正则) 则将response的origin设为请求者域名
 * @author cc
 * @Date 2016/11/8
 * @value 1.0
 */
public class AccessControlFilter implements Filter {

    private Pattern pattern;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String originPattern = filterConfig.getInitParameter("originPattern");
        if (StringUtils.isBlank(originPattern)) {
            throw new ServletException("init param originPattern MUST be set");
        }
        pattern = Pattern.compile(originPattern);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // 跨域
//        String origin = httpRequest.getHeader("origin");

        //未跨域
//        if (StringUtils.isBlank(origin)) {
            httpResponse.addHeader("Access-Control-Allow-Origin", "*");
            httpResponse.addHeader("Access-Control-Allow-Headers", "Origin, x-requested-with, Content-Type, Accept,X-Cookie");
            httpResponse.addHeader("Access-Control-Allow-Credentials", "true");
//        } else if (pattern.matcher(origin).matches()) {//跨域 只允许特定域名
//            httpResponse.addHeader("Access-Control-Allow-Origin", origin);
//            httpResponse.addHeader("Access-Control-Allow-Headers", "Origin, x-requested-with, Content-Type, Accept,X-Cookie");
//            httpResponse.addHeader("Access-Control-Allow-Credentials", "true");
//        } else {//no match
//            return;
//        }

        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
